<?php


namespace app\api\controller\v2;


use app\controller\Base;
use app\model\Baby;
use app\model\Members;
use app\model\Milk;
use think\facade\Db;
use think\Request;

class BabyMembers extends Base
{

    //添加用户
    public function addMembers(Request $request){

        $data = $request->param();

        $id = Members::create($data)->getData('id');

        if (empty($id)){
            return $this->create($id,'自动生成账号失败',400);
        }else{
            return $this->create($id,'自动生成账号成功',200);
        }

    }

    //通过用户ID获取默认

    //[用户user_id,宝宝bb_id,是否统计isCount[0,1]]
    //getlastday(1,0,0)
    public function getlastday(Request $request){
      //DONE：测试获取最近一条记录

        $data = $request->param();

        //组合查询条件
        $map = [];
        $map[] = ['b.user_id','=',$data['user_id']];

        //检查参数并组合查询条件：[用户user_id,[默认项isChoose=0/1],[宝宝bb_id]]
        if ($data['bb_id'] > 0){
            //只要带有宝宝ID则读取宝宝ID数据，否则读取默认数据
            $map[] = ['b.bb_id','=',$data['bb_id']];
        }else{
            $map[] = ['isChoose','=',1];
        }



        //1、默认页面：获取登录用户ID-》查找默认宝宝ID-》返回该宝宝所有记录/当天记录

//            iscount=1获取当天次数，0为获取列表
        if ($data['isCount']==1){
            $result = Db::table('zh_baby')->alias('m')
                ->join('zh_milk b','b.bb_id=m.id')
                ->where($map)
                ->whereDay('b.create_time')
                ->count();
        }elseif ($data['isCount']==0){
            $result = Db::table('zh_baby')->alias('m')
                ->join('zh_milk b','b.bb_id=m.id')
                ->where($map)
                ->order('b.id','desc')
                ->limit(6)
                ->select();

            if ($result->isEmpty()){
                return $this->create($result,'没有数据',204);
            }

        }else{

            return $this->create([],'参数错误',400);
        }

        //halt($data,$map,$result);

        //拼接参数到返回结果：$result['params'] = $data;


            return $this->create($result,'请求成功',200);


        //页面头部：默认记录（最近一条和统计次数）；中部：当前用户喂养记录/指定宝宝喂养记录
    }


    //获取用户基本信息
    public function getUserInfo(Request $request){
        $uid = $request->param('uid');
        $res = Members::where('id',$uid)->find();
        $defaultBabyId = Baby::where([['user_id','=',$uid],['ischoose','=',1]])->field('id')->find();
        $res['bid'] = $defaultBabyId['id'];
        //把默认选项也传给前端
        if (empty($res)){
            return $this->create(null,'参数错误',204);
        }else{
            return $this->create($res,'请求成功',200);
        }
    }
}